package com.ceair.mub2c.payment.payments.utils;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * default aaaa1111 E1XQS1EIE/L6Y24th0r2FA==
 * @author Administrator
 *
 */
public class AES {
	
	private static final Logger LOG = LoggerFactory.getLogger(AES.class);
	
	/** AES Key : 每个工程需重新指定 */
	// private static final String KEY = "IUWGffP42UBiqu0d";
	
	private static final String ENCODE = "UTF-8";
	
	private static final String FORMAT = "AES";
	
	private static final String FORMATION = "AES/ECB/PKCS5Padding";

	private AES() {
		
	}
	
    /**
     * 加密
     * @param sSrc
     * @return
     */
    public static String encrypt(String sSrc, String key) {
        if (key == null) {
        	LOG.error("Key为空null");
            return null;
        }
        // 判断Key是否为16位
       /* if (key.length() != 16) {
        	LOG.error("Key长度不是16位");
            return null;
        }*/
        try {
        	
	        byte[] raw = ConvertTools.hexStringToByte(key);
	        SecretKeySpec skeySpec = new SecretKeySpec(raw, FORMAT);
	        Cipher cipher = Cipher.getInstance(FORMATION);//"算法/模式/补码方式"
	        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
	        byte[] encrypted = cipher.doFinal(sSrc.getBytes(ENCODE));
	        //此处使用BASE64做转码功能，同时能起到2次加密的作用。
	        String resultStr = Base64.encodeBase64String(encrypted);
	        if (resultStr != null && resultStr.lastIndexOf("\r\n") != -1) {
				resultStr = resultStr.substring(0, resultStr.lastIndexOf("\r\n"));
			}
	        return resultStr;
        } catch (UnsupportedEncodingException e) {
			LOG.error("encrypt failed. ", e);
		} catch (GeneralSecurityException e) {
			LOG.error("encrypt failed. ", e);
		}
        return null;
    }

    /** 
     * 解密
     * @param sSrc
     * @return
     */
    public static String decrypt(String sSrc, String key) {
        try {
        	// 判断Key是否正确
        	if (key == null) {
        		LOG.error("Key为空null");
        		return null;
        	}
        	// 判断Key是否为16位
        	/*if (key.length() != 16) {
        		LOG.error("Key长度不是16位");
        		return null;
        	}*/
        	byte[] raw = ConvertTools.hexStringToByte(key);
        	SecretKeySpec skeySpec = new SecretKeySpec(raw, FORMAT);
        	Cipher cipher = Cipher.getInstance(FORMATION);
        	cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        	byte[] encrypted = Base64.decodeBase64(sSrc);//先用base64解密
        	byte[] original = cipher.doFinal(encrypted);
        	String originalString = new String(original,ENCODE);
        	return originalString;
		} catch (UnsupportedEncodingException e) {
			LOG.error("decrypt failed. ", e);
		} catch (GeneralSecurityException e) {
			LOG.error("decrypt failed. ", e);
		}
        return null;
    }
    
    public static void main(String[] args) {
    	String key = "00d3e52bf6e68b7d669ee9a918dd347b5423a89e2937604e3a5b50f2d8d1edb0";
    	String enc = "AHY+cTAzAHFE0cxJcFz/cKAGegK2P/MVJy+CwoOH9eY69Tlk79Ag5xwTEOPTQXNjoqU8OhF4IdY68AMVx+/o1MTSSPRhzI8UW0DT0o0KlVOl2BhfT3xWwhUa21Qw4uRD/OHIzZW05cb0eFbzUuTYgdp2V2JeQ+txVART4qLjFSsKvuIk0H6OeClZ33Hi3GOX";
    	
    	System.out.println("AES ENC:" + enc);
		System.out.println("AES DEC:" + decrypt(enc, key));
		// byte[] raw = ConvertTools.hexStringToByte(key);
		String dec = "{\"reqId\":\"a0032cc8-be74-48ec-a37a-94382e33d52a\",\"customerId\":\"653010765033\",\"userType\":\"mufly\",\"orgCode\":\"ceair\",\"randType\":\"1\"}";
		System.out.println("AES DEC:" + dec);
		System.out.println("AES ENC:" + encrypt(dec, key));
    	
//		String dec = "{\"cardNo\":\"1\",\"messageTaskId\":\"1\",\"messageCode\":\"1\",\"mobile\":\"1\",\"idNo\":\"1\",\"idType\":\"1\",\"userName\":\"1\",\"userType\":\"1\",\"customerId\":\"1\",\"reqId\":\"1\"}";
//		String enc = encrypt(dec, key);
//		System.out.println("AES ENC:" + enc);
//		System.out.println("AES DEC:" + decrypt("aVSoLcuOKNk/ZFwXI5DTkYnJ43RBLlQL20Rl1raIIoFPjffXVrk4UgOrbItmK41Ni9zcw5xySK/jMV3MCOo/ak1CO05XtMDRPV63Ge6nQHs=", key));
	}
}
